package com.gxg.services;

import com.gxg.dao.CourseDao;
import com.gxg.dao.ExperimentalCheckWorkDao;
import com.gxg.dao.ExperimentalDocumentDao;
import com.gxg.dao.ExperimentalEnvironmentDao;
import com.gxg.dao.ExperimentalReportDao;
import com.gxg.dao.StudentUserDao;
import com.gxg.dao.UserDao;
import com.gxg.dockerapi.DockerImageAPI;
import com.gxg.entities.Course;
import com.gxg.entities.ExperimentalCheckWork;
import com.gxg.entities.ExperimentalDocument;
import com.gxg.entities.ExperimentalEnvironment;
import com.gxg.entities.ExperimentalNode;
import com.gxg.entities.ExperimentalReport;
import com.gxg.entities.StudentUser;
import com.gxg.entities.User;

import java.awt.image.RescaleOp;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;

import com.gxg.video.GetVideoFirst;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

@Service
public class CourseService {
  @Value("${course.img.dir}")
  private String courseImgDir;
  @Value("${user.resources.url}")
  private String userResourcesUrl;
  @Autowired
  private CourseDao courseDao;
  @Autowired
  private StudentUserDao studentUserDao;
  @Autowired
  private ExperimentalCheckWorkDao experimentalCheckWorkDao;
  @Autowired
  private ExperimentalDocumentDao experimentalDocumentDao;
  @Autowired
  private FileService fileService;
  @Autowired
  GetVideoFirst getVideoFirst;
  @Value("${course.page.amount}")
  private int coursePageAmount;
  @Value("${teacher.course.page.amount}")
  private int teacherCoursePageAmount;
  @Value("http://192.168.2.36:2375")
  private String dockerServerIp;
  @Autowired
  private ExperimentalEnvironmentDao experimentalEnvironmentDao;
  @Value("${experimental.environment.url}")
  private String experimentalEnvironmentUrl;
  @Autowired
  private FtpService ftpService;
  @Autowired
  private VNCService vncService;
  @Value("${experimental.node.username}")
  private String username;
  @Value("${experimental.node.password}")
  private String password;
  @Autowired
  private SftpService sftpService;
  @Value("${sftp.port}")
  private Integer sftpPort;
  @Autowired
  private UserDao userDao;
  @Autowired
  private ExperimentalReportDao experimentalReportDao;
  @Value("${experimental_report_page_amount}")
  private int experimentalReportPageAmount;

  /**
   * 该方法用于创建新课程
   *
   * @param courseTap      课程标签
   * @param courseName     课程名称
   * @param courseDescribe 课程描述
   * @param courseImage    课程图片
   * @param user           创建人
   * @return
   */
  public String createCourse(String courseTap, String courseName, String courseDescribe, MultipartFile courseImage, User user) {

    if (courseTap == null || courseTap.equals("") || courseName.equals("") || courseName == null || courseDescribe == null || courseDescribe.equals("")) {
      return "所有字段不能为空！";
    } else {
      if (user.getRole().equals("教师")) {
        String teacher;
        Timestamp time;
        String id;
        String imgName;
        if (!courseImage.isEmpty()) {
          synchronized (this) {
            try {
              teacher = user.getId();
              String fileName = courseImage.getOriginalFilename();//获取上传文件的文件名
              String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);//获取文件后缀名
              time = new Timestamp(System.currentTimeMillis());
              String timeString = time.toString();
              id = teacher + timeString.split(" ")[0].split("-")[0] + timeString.split(" ")[0].split("-")[1] + timeString.split(" ")[0].split("-")[2] + timeString.split(" ")[1].split(":")[0] + timeString.split(" ")[1].split(":")[1] + timeString.split(" ")[1].split(":")[2].split("\\.")[0];//注意，split是按照正则表达式进行分割，.在正则表达式中为特殊字符，需要转义。
              while (courseDao.getCourseCountById(id) != 0) {
                Random random = new Random(100);
                Long idLong = Long.parseLong(id);
                idLong += random.nextLong();
                id = idLong + "";
                if (id.length() > 22) {
                  id = id.substring(0, 23);
                }
              }
              imgName = id + "." + fileType;
              File uploadDir = new File(courseImgDir);
              //如果上传目录不存在则创建
              if (!uploadDir.exists()) {
                uploadDir.mkdirs();
              }
              BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(new File(courseImgDir, imgName)));
              outputStream.write(courseImage.getBytes());
              outputStream.flush();
              outputStream.close();
            } catch (FileNotFoundException e) {
              e.printStackTrace();
              return "上传图片失败：" + e.getMessage();
            } catch (IOException e) {
              e.printStackTrace();
              return "上传图片失败：" + e.getMessage();
            }
            try {
              courseDao.createCourse(id, courseName, courseTap, courseDescribe, imgName, teacher, time, time);
            } catch (Exception e) {
              System.out.println(e.getMessage());
              String deleteImgResult = fileService.deleteFile(courseImgDir + imgName);
              System.out.println(deleteImgResult);
              return "操作数据库失败！";
            }
            return "ok";
          }
        } else {
          return "上传的图片为空！";
        }
      } else {
        return "您的身份是学生，仅有教师可以创建课程！";
      }
    }
  }

  /**
   * 该方法用于创建实验（自己编写）
   *
   * @param experimentalTitle   实验题目
   * @param experimentalContent 实验内容
   * @param courseId            课程表示
   * @param user                创建用户
   * @return
   */
  public String createExperimental(String experimentalTitle, String experimentalContent, String courseId, User user) {
    if (experimentalContent.equals("") || experimentalContent == null) {
      return "您的实验内容为空！";
    } else {
      if (user.getRole().equals("教师")) {
//                String teacherId = user.getId();
        String experimentalId;
        Timestamp time;
        String experimentalSrc;
        String experimentalName;
        synchronized (this) {
          try {
            time = new Timestamp(System.currentTimeMillis());
            String timeString = time.toString();
            experimentalId = timeString.split(" ")[0].split("-")[0] + timeString.split(" ")[0].split("-")[1] + timeString.split(" ")[0].split("-")[2] + timeString.split(" ")[1].split(":")[0] + timeString.split(" ")[1].split(":")[1] + timeString.split(" ")[1].split(":")[2].split("\\.")[0];
            while (experimentalDocumentDao.getExperimentalDocumentCountById(experimentalId) != 0) {
              Random random = new Random(100);
              Long experimentalIdLong = Long.parseLong(experimentalId);
              experimentalIdLong += random.nextLong();
              experimentalId = experimentalIdLong + "";
              if (experimentalId.length() > 14) {
                experimentalId.substring(0, 15);
              }
            }
            experimentalName = experimentalId + ".html";
            experimentalSrc = userResourcesUrl + "course/experimental/" + courseId + "/";
            File uploadDir = new File(experimentalSrc);
            //如果上传目录不存在则创建
            if (!uploadDir.exists()) {
              uploadDir.mkdirs();
            }
            File file = new File(experimentalSrc + experimentalName);
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            byte by[] = experimentalContent.getBytes();
            fileOutputStream.write(by);
            fileOutputStream.close();
          } catch (FileNotFoundException e) {
            e.printStackTrace();
            return "往服务器中写入实验内容时失败：" + e.getMessage();
          } catch (IOException e) {
            e.printStackTrace();
            return "往服务器中写入实验内容时失败：" + e.getMessage();
          }
          try {
            experimentalDocumentDao.createExperimentalDocumental(experimentalId, experimentalTitle, experimentalName, courseId, time, time);
          } catch (Exception e) {
            System.out.println(e.getMessage());
            System.out.println(fileService.deleteFile(experimentalSrc + experimentalName));
            return "操作数据库失败！";
          }
          try {
            courseDao.updateModificationTimeById(time, courseId);
          } catch (Exception e) {
            System.out.println(e.getMessage());
          } finally {
            return "ok";
          }
        }
      } else {
        return "您的身份是学生，仅有教师可以编写实验！";
      }
    }
  }


  public String getMyCourses(String page, User user) {
    if (user.getRole().equals("学生")) {
      return "您的身份是学生，仅有教师可以编写实验！";
    }
    int pageInt = 1;
    try {
      pageInt = Integer.parseInt(page);
    } catch (Exception e) {
      return "页数出错！";
    }
    int coursesCount = this.courseDao.getCoursesCountByTeacher(user.getId());
    if (coursesCount == 0) {
      return "暂无课程！";
    }
    if (coursesCount <= (pageInt - 1) * this.teacherCoursePageAmount) {
      return "超出页数！";
    }
    List<Course> courseList = this.courseDao.getCoursesByTeacherAndPage(user.getId(), pageInt);
    int pageCount = coursesCount % this.teacherCoursePageAmount == 0 ? coursesCount / this.teacherCoursePageAmount : coursesCount / this.teacherCoursePageAmount + 1;
    JSONObject coursesJson = new JSONObject();
    coursesJson.accumulate("pageCount", Integer.valueOf(pageCount));
    coursesJson.accumulate("courseList", courseList);
    return coursesJson.toString();
  }

  public String getCourseInfoById(String courseId) {
    Course course = this.courseDao.getCourseById(courseId);
    if (course == null) {
      return "没有该课程！";
    }
    return course.toString();
  }

  public String getCoursesCountByTeacher(String teacher) {
    return this.courseDao.getCoursesCountByTeacher(teacher) + "";
  }

  public String getCoursesTop5ByTeacher(String teacher) {
    List<Course> courseList = this.courseDao.getCoursesTop5ByTeacher(teacher);
    if (courseList == null) {
      return "没有课程！";
    }
    JSONObject jsonObject = new JSONObject();
    jsonObject.accumulate("teacherCourses", courseList);
    return jsonObject.toString();
  }

  public String uploadExperimentalImg(MultipartFile ExperimentalImage) {
    String imgName;
    synchronized (this) {
      try {
        String fileName = ExperimentalImage.getOriginalFilename();
        String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
        Timestamp time = new Timestamp(System.currentTimeMillis());
        String timeString = time.toString();
        String imgId = timeString.split(" ")[0].split("-")[0] + timeString.split(" ")[0].split("-")[1] + timeString.split(" ")[0].split("-")[2] + timeString.split(" ")[1].split(":")[0] + timeString.split(" ")[1].split(":")[1] + timeString.split(" ")[1].split(":")[2].split("\\.")[0];
        imgName = imgId + "." + fileType;
        String experimentalImgUrl = this.userResourcesUrl + "course/experimental/img/";
        File uploadDir = new File(experimentalImgUrl);
        if (!uploadDir.exists()) {
          uploadDir.mkdirs();
        }
        while (new File(experimentalImgUrl, imgName).exists()) {
          Long imgIdLong = Long.valueOf(Long.parseLong(imgId));
          Random random = new Random(100L);
          imgIdLong = Long.valueOf(imgIdLong.longValue() + random.nextLong());
          imgId = imgIdLong + "";
          imgName = imgId + "." + fileType;
        }
        BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(new File(experimentalImgUrl, imgName)));
        outputStream.write(ExperimentalImage.getBytes());
        outputStream.flush();
        outputStream.close();
      } catch (FileNotFoundException e) {
        e.printStackTrace();
        return "error";
      } catch (IOException e) {
        e.printStackTrace();
        return "error";
      }
    }
    return "/user/course/experimental/img/" + imgName;
  }

  public String getCourseExperimental(String courseId) {
    List<ExperimentalDocument> experimentalDocumentList = this.experimentalDocumentDao.getExperimentalDocumentByCourseId(courseId);
    if (experimentalDocumentList == null) {
      return "该课程暂时没有实验内容！";
    }
    JSONObject jsonObject = new JSONObject();
    ArrayList<ExperimentalDocument> experimentalDocumentArrayList = new ArrayList();
    for (int i = 0; i < experimentalDocumentList.size(); i++) {
      experimentalDocumentArrayList.add(experimentalDocumentList.get(i));
    }
    jsonObject.accumulate("experimentalDocument", experimentalDocumentArrayList);
    return jsonObject.toString();
  }

  public String getCourseExperimentalTop5(String courseId) {
    List<ExperimentalDocument> experimentalDocumentList = this.experimentalDocumentDao.getExperimentalDocumentTop5ByCourseId(courseId);
    if (experimentalDocumentList == null) {
      return "该课程暂时没有实验内容！";
    }
    JSONObject jsonObject = new JSONObject();
    ArrayList<ExperimentalDocument> experimentalDocumentArrayList = new ArrayList();
    for (int i = 0; i < experimentalDocumentList.size(); i++) {
      experimentalDocumentArrayList.add(experimentalDocumentList.get(i));
    }
    jsonObject.accumulate("experimentalDocument", experimentalDocumentArrayList);
    return jsonObject.toString();
  }

  public String getExperimetalInformation(String experimentalId) {
    ExperimentalDocument experimentalDocument = this.experimentalDocumentDao.getExperimentalDocumentById(experimentalId);
    if (experimentalDocument == null) {
      return "error:没有该实验！";
    }
    String title = experimentalDocument.getTitle();
    String courseId = experimentalDocument.getCourseId();
    String name = experimentalDocument.getName();
    String fileType = name.substring(name.lastIndexOf(".") + 1);
    if (fileType.equals("pdf")) {
      JSONObject jsonObject = new JSONObject();
      jsonObject.accumulate("title", title);
      jsonObject.accumulate("content", "pdf");
      jsonObject.accumulate("experimentalUrl", "/user/course/experimental/" + courseId + "/" + name);
      return jsonObject.toString();
    }
    String fileUrl = this.userResourcesUrl + "course/experimental/" + courseId + "/" + name;
    File file = new File(fileUrl);
    if (file.exists()) {
      try {
        BufferedReader bufferedReader = new BufferedReader(new FileReader(fileUrl));

        String content = "";
        String temp;
        while ((temp = bufferedReader.readLine()) != null) {
          content = content + temp;
          content = content + "\n";
        }
        bufferedReader.close();
        JSONObject jsonObject = new JSONObject();
        jsonObject.accumulate("title", title);
        jsonObject.accumulate("content", content);
        return jsonObject.toString();
      } catch (Exception e) {
        e.printStackTrace();
        return "error:" + e.getMessage();
      }
    }
    return "error:服务器没有该实验文档，可能该实验文档丢失！";
  }

  public String uploadExperimentalDocument(String courseId, String experimentalDocumentTitle, MultipartFile experimentalDocument) {
    if (courseDao.getCourseCountById(courseId) == 0) {
      return "没有该课程！";
    } else {
      if (experimentalDocumentTitle == null || experimentalDocumentTitle.equals("")) {
        return "实验题目不能为空！";
      } else {
        String id;
        Timestamp time;
        String name;
        String uploadDir;
        if (!experimentalDocument.isEmpty()) {
          synchronized (this) {
            try {
              String fileName = experimentalDocument.getOriginalFilename();//获取上传文件的文件名
              String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);//获取文件后缀名
              time = new Timestamp(System.currentTimeMillis());
              String timeString = time.toString();
              id = timeString.split(" ")[0].split("-")[0] + timeString.split(" ")[0].split("-")[1] + timeString.split(" ")[0].split("-")[2] + timeString.split(" ")[1].split(":")[0] + timeString.split(" ")[1].split(":")[1] + timeString.split(" ")[1].split(":")[2].split("\\.")[0];//注意，split是按照正则表达式进行分割，.在正则表达式中为特殊字符，需要转义。
              while (experimentalDocumentDao.getExperimentalDocumentCountById(id) != 0) {
                Random random = new Random(100);
                Long idLong = Long.parseLong(id);
                idLong += random.nextLong();
                id = idLong + "";
                if (id.length() > 14) {
                  id = id.substring(0, 15);
                }
              }
              name = id + "." + fileType;
              uploadDir = userResourcesUrl + "/course/experimental/" + courseId + "/";
              File uploadFileDir = new File(uploadDir);
              if (!uploadFileDir.exists()) {
                uploadFileDir.mkdirs();
              }
              BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(new File(uploadDir, name)));
              outputStream.write(experimentalDocument.getBytes());
              outputStream.flush();
              outputStream.close();
            } catch (FileNotFoundException e) {
              e.printStackTrace();
              return "上传文档失败：" + e.getMessage();
            } catch (IOException e) {
              e.printStackTrace();
              return "上传文档失败：" + e.getMessage();
            }
            try {
              experimentalDocumentDao.createExperimentalDocumental(id, experimentalDocumentTitle, name, courseId, time, time);
            } catch (Exception e) {
              System.out.println(e.getMessage());
              String deleteFileResult = fileService.deleteFile(uploadDir + name);
              if (!deleteFileResult.equals("ok")) {
                System.out.println(deleteFileResult);
              }
              return "操作数据库失败！";
            }
            try {
              courseDao.updateModificationTimeById(time, courseId);
            } catch (Exception e) {
              System.out.println(e.getMessage());
            } finally {
              return "上传成功！";
            }
          }
        } else {
          return "文件为空！";
        }
      }
    }
  }

  public String editCourseInformation(String courseId, String courseName, String courseDescription) {
    if ((courseId.equals("")) || (courseId == null)) {
      return "无法正确获得课程编号，请确认系统生成的url是否正确！";
    }
    if ((courseName.equals("")) || (courseName == null)) {
      return "课程名称不能为空！";
    }
    if ((courseDescription.equals("")) || (courseDescription == null)) {
      return "课程描述不能为空！";
    }
    if (courseName.length() > 200) {
      return "课程名称不能超过200字符！";
    }
    if (courseDescription.length() > 800) {
      return "课程描述不能超过800字符！";
    }
    if (this.courseDao.getCourseCountById(courseId) == 0) {
      return "没有该课程编号的课程，可能系统生成的url发生改动，或课程已经被删除！";
    }
    Timestamp time = new Timestamp(System.currentTimeMillis());
    try {
      this.courseDao.updateNameAndDescriptionAndModificationTimeById(courseId, courseName, courseDescription, time);
      return "ok";
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }
    return "操作数据库失败！";
  }

  /**
   * 该方法用于删除课程信息
   *
   * @param courseId 课程id
   * @return
   */
  public String deleteCourse(String courseId, User user) {
    if (courseId.equals("") || courseId == null) {
      return "不能获得课程号，请确认系统生成的url是否正确！";
    } else {
      if (courseDao.getCourseCountById(courseId) == 0) {
        return "没有该课程编号的课程，可能系统生成的url发生改动，或课程已经被删除！";
      } else {
        Course course = courseDao.getCourseById(courseId);
        if (course == null) {
          return "没有该课程编号的课程，可能系统生成的url发生改动，或课程已经被删除！";
        } else {
          int experimentDocumentCount = experimentalDocumentDao.getExperimentalDocumentCountByCourseId(courseId);
          if (experimentDocumentCount != 0) {
            String deleteExperimentalDocumentAllResult = "";
            List<ExperimentalDocument> experimentalDocumentList = experimentalDocumentDao.getExperimentalDocumentByCourseId(courseId);
            for (ExperimentalDocument experimentalDocument : experimentalDocumentList) {
              String deleteExperimentalDocumentResult = this.deleteExperimentalDocument(experimentalDocument.getId(), user);
              if (!("ok".equals(deleteExperimentalDocumentResult))) {
                deleteExperimentalDocumentAllResult += "删除实验文档" + experimentalDocument.getId() + "出错：" + deleteExperimentalDocumentResult + "\n";
              }
            }
            if (!("".equals(deleteExperimentalDocumentAllResult))) {
              deleteExperimentalDocumentAllResult += "其他实验文档已经删除成功！实验课程没有被删除！";
              return deleteExperimentalDocumentAllResult;
            }
          }
          String courseImgPath = courseImgDir + course.getImg();
          String deleteImgResult = fileService.deleteFile(courseImgPath);
          if (deleteImgResult.equals("ok") || deleteImgResult.equals("删除文件失败：文件不存在！")) {
            if (deleteImgResult.equals("删除文件失败：文件不存在！")) {
              System.out.println(deleteImgResult);
            }

            try {
              courseDao.deleteCourseById(courseId);
              return "ok";
            } catch (Exception e) {
              System.out.println(e.getMessage());
              return "删除课程失败：操作数据库出错！但是课程图片和实验文档及实验报告已经删除！";
            }
          } else {
            return "因系统原因删除课程图片失败，导致删除课程失败！";
//                        if(deleteImgResult.equals("删除文件失败：文件不存在！")) {
//                            return "系统没有找到课程图片，因此导致删除课程失败！";
//                        } else {
//                            return "因系统原因删除课程图片失败，导致删除课程失败！";
//                        }
          }
        }
      }
    }
  }

  /**
   * 该方法用于处理修改实验文档
   *
   * @param experimentalId      实验id
   * @param experimentalTitle   实验题目
   * @param experimentalContent 实验内容
   * @param user                修改人
   * @return
   */
  public String editExperimentalDocument(String experimentalId, String experimentalTitle, String experimentalContent, User user) {
    if (experimentalTitle == null || experimentalTitle.equals("")) {
      return "实验题目不能为空！";
    } else {
      if (experimentalTitle.length() > 200) {
        return "实验题目不能超过200字符！";
      } else {
        if (user.getRole().equals("教师")) {
          if (experimentalDocumentDao.getExperimentalDocumentCountById(experimentalId) == 0) {
            return "没有找到对应实验，可能系统生成的url被改变，或服务器删除了该实验信息！";
          } else {
            if (experimentalContent == null || experimentalContent.equals("")) {
              return "实验内容为空！";
            } else {
              ExperimentalDocument experimentalDocument = experimentalDocumentDao.getExperimentalDocumentById(experimentalId);
              if (experimentalDocument == null) {
                return "没有找到对应实验，可能系统生成的url被改变，或服务器删除了该实验信息！";
              } else {
                String experimentalName = experimentalDocument.getName();
                String courseId = experimentalDocument.getCourseId();
                String experimentalSrc = userResourcesUrl + "course/experimental/" + courseId + "/";
                String writeFileResult = fileService.writeFile(experimentalSrc, experimentalName, experimentalContent);
                if (writeFileResult.equals("ok")) {
                  Timestamp time = new Timestamp(System.currentTimeMillis());
                  try {
                    experimentalDocumentDao.updateTitleAndModificationTimeById(experimentalId, experimentalTitle, time);
                  } catch (Exception e) {
                    System.out.println(e.getMessage());
                    return "操作数据库失败！";
                  }
                  try {
                    courseDao.updateModificationTimeById(time, courseId);
                  } catch (Exception e) {
                    System.out.println(e.getMessage());
                  } finally {
                    return "ok";
                  }
                } else {
                  return writeFileResult;
                }
              }
            }
          }
        } else {
          return "抱歉，您的身份是学生，仅有教师可以修改实验！";
        }
      }
    }
  }

  /**
   * 该方法用于修改实验文档标题
   *
   * @param experimentalId    实验id
   * @param experimentalTitle 实验标题
   * @param user              修改人
   * @return
   */
  public String editExperimentalDocumentTitle(String experimentalId, String experimentalTitle, User user) {
    if (experimentalTitle == null || experimentalTitle.equals("")) {
      return "实验题目不能为空！";
    } else {
      if (experimentalTitle.length() > 200) {
        return "实验题目长度不能超过200字符！";
      } else {
        if (user.getRole().equals("教师")) {
          if (experimentalDocumentDao.getExperimentalDocumentCountById(experimentalId) == 0) {
            return "没有找到该实验相关信息，可能服务器已经删除该实验！";
          } else {
            ExperimentalDocument experimentalDocument = experimentalDocumentDao.getExperimentalDocumentById(experimentalId);
            if (experimentalDocument == null) {
              return "没有找到该实验相关信息，可能服务器已经删除该实验！";
            } else {
              Timestamp time = new Timestamp(System.currentTimeMillis());
              try {
                experimentalDocumentDao.updateTitleAndModificationTimeById(experimentalId, experimentalTitle, time);
              } catch (Exception e) {
                System.out.println(e.getMessage());
                return "操作数据库失败！";
              }
              try {
                courseDao.updateModificationTimeById(time, experimentalDocument.getCourseId());
              } catch (Exception e) {
                System.out.println(e.getMessage());
              } finally {
                return "ok";
              }
            }
          }
        } else {
          return "您的身份是学生，仅有教师可以修改实验！";
        }
      }
    }
  }

  public String editExperimentalDocumentContent(String editExperimentalDocumentContentPdfExperimentalId, MultipartFile editExperimentalDocumentInput, User user) {
    if (user.getRole().equals("教师")) {
      if (this.experimentalDocumentDao.getExperimentalDocumentCountById(editExperimentalDocumentContentPdfExperimentalId) == 0) {
        return "没有找到该实验相关信息，可能系统已经删除该实验信息！";
      }
      ExperimentalDocument experimentalDocument = this.experimentalDocumentDao.getExperimentalDocumentById(editExperimentalDocumentContentPdfExperimentalId);
      if (experimentalDocument == null) {
        return "没有找到该实验相关信息，可能系统已经删除该实验信息！";
      }
      String fileName = editExperimentalDocumentInput.getOriginalFilename();
      String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
      if ((fileType.equals("pdf")) || (fileType.equals("html")) || (fileType.equals("htm"))) {
        String courseId = experimentalDocument.getCourseId();
        String path = this.userResourcesUrl + "/course/experimental/" + courseId + "/";
        String name = editExperimentalDocumentContentPdfExperimentalId + "." + fileType;
        String uploadFileResult = this.fileService.uploadFile(editExperimentalDocumentInput, name, path);
        if (uploadFileResult.equals("ok")) {
          Timestamp time = new Timestamp(System.currentTimeMillis());
          try {
            this.experimentalDocumentDao.updateModificationTimeById(editExperimentalDocumentContentPdfExperimentalId, time);
            this.courseDao.updateModificationTimeById(time, courseId);
          } catch (Exception e) {
            System.out.println(e.getMessage());
          } finally {
            return "ok";
          }
        }
        return uploadFileResult;
      }
      return "仅支持上传pdf或html格式的文件，暂不支持其他类型文件！";
    }
    return "抱歉，您的身份是学生，仅有教师可以修改实验！";
  }

  public String deleteExperimentalDocument(String experimentalId, User user) {
    if (user.getRole().equals("教师")) {
      if (this.experimentalDocumentDao.getExperimentalDocumentCountById(experimentalId) == 0) {
        return "没有找到该实验信息，可能系统已经删除该实验！";
      }
      ExperimentalDocument experimentalDocument = this.experimentalDocumentDao.getExperimentalDocumentById(experimentalId);
      if (experimentalDocument == null) {
        return "没有找到该实验信息，可能系统已经删除该实验！";
      }
      int experimentalReportCount = this.experimentalReportDao.getExperimentalReportCountByExperimentalId(experimentalId);
      if (experimentalReportCount != 0) {
        List<ExperimentalReport> experimentalReportList = this.experimentalReportDao.getExperimentalReportByExperimentalIdAndStartLimitAndEndLimit(experimentalId, 0, experimentalReportCount);
        String deleteExperimentalReportAllResult = "";
        for (ExperimentalReport experimentalReport : experimentalReportList) {
          String deleteExperimentalReportResult = deleteExperimentalReport(experimentalReport.getId(), user);
          if (!"ok".equals(deleteExperimentalReportResult)) {
            deleteExperimentalReportAllResult = deleteExperimentalReportAllResult + "删除" + experimentalReport.getId() + "实验报告出错：" + deleteExperimentalReportResult + "\n";
          }
        }
        if (!"".equals(deleteExperimentalReportAllResult)) {
          deleteExperimentalReportAllResult = deleteExperimentalReportAllResult + "其他实验报告删除成功！该实验文档没有删除！";
          return deleteExperimentalReportAllResult;
        }
      }
      String experimentalName = experimentalDocument.getName();
      String courseId = experimentalDocument.getCourseId();
      String path = this.userResourcesUrl + "course/experimental/" + courseId + "/" + experimentalName;
      String deleteFileResult = this.fileService.deleteFile(path);
      if ((deleteFileResult.equals("ok")) || (deleteFileResult.equals("删除文件失败：文件不存在！"))) {
        if (deleteFileResult.equals("删除文件失败：文件不存在！")) {
          System.out.println(deleteFileResult);
        }
        Timestamp time = new Timestamp(System.currentTimeMillis());
        try {
          this.experimentalDocumentDao.deleteExperimentalDocumentById(experimentalId);
        } catch (Exception e) {
          System.out.println(e.getMessage());
          return "删除实验失败：更新数据库失败，但实验文档已经被删除！";
        }
        try {
          this.courseDao.updateModificationTimeById(time, courseId);
        } catch (Exception e) {
          System.out.println(e.getMessage());
        }
        return "ok";
      }
      return "删除实验文档失败";
    }
    return "抱歉，您的身份是学生，仅有教师可以修改实验！";
  }

  public String getCoursesTopNumber(int number) {
    if (this.courseDao.getCoursesCount() == 0) {
      return "暂无课程！";
    }
    List<Course> courseList = this.courseDao.getCoursesTopNumber(number);
    if (courseList == null) {
      return "暂无课程！";
    }
    JSONObject coursesJson = new JSONObject();
    coursesJson.accumulate("courseList", courseList);
    return coursesJson.toString();
  }

  public String getCoursesCountByTab(String[] coursesTab) {
    ArrayList<Integer> coursesCountList = new ArrayList();
    for (int i = 0; i < coursesTab.length; i++) {
      coursesCountList.add(Integer.valueOf(this.courseDao.getCoursesCountByTab(coursesTab[i])));
    }
    JSONObject jsonObject = new JSONObject();
    jsonObject.accumulate("coursesCountList", coursesCountList);
    return jsonObject.toString();
  }

  public String getCoursesByTabAndPage(String tab, int page) {
    if (tab.equals("all")) {
      int coursesCount = this.courseDao.getCoursesCount();
      if (coursesCount == 0) {
        return "暂无课程！";
      }
      int coursesPageCount = coursesCount % this.coursePageAmount == 0 ? coursesCount / this.coursePageAmount : coursesCount / this.coursePageAmount + 1;
      if (page > coursesPageCount) {
        return "超出页数！";
      }
      List<Course> courseList = this.courseDao.getCoursesByLimit(this.coursePageAmount * (page - 1), this.coursePageAmount);
      if (courseList == null) {
        return "暂无课程！";
      }
      JSONObject jsonObject = new JSONObject();
      jsonObject.accumulate("courseList", courseList);
      jsonObject.accumulate("pageCount", Integer.valueOf(coursesPageCount));
      return jsonObject.toString();
    }
    int coursesCount = this.courseDao.getCoursesCountByTab(tab);
    if (coursesCount == 0) {
      return "暂无课程！";
    }
    int coursesPageCount = coursesCount % this.coursePageAmount == 0 ? coursesCount / this.coursePageAmount : coursesCount / this.coursePageAmount + 1;
    if (page > coursesPageCount) {
      return "超出页数！";
    }
    List<Course> courseList = this.courseDao.getCoursesByTabAndLimit(tab, this.coursePageAmount * (page - 1), this.coursePageAmount);
    if (courseList == null) {
      return "暂无课程！";
    }
    JSONObject jsonObject = new JSONObject();
    jsonObject.accumulate("courseList", courseList);
    jsonObject.accumulate("pageCount", Integer.valueOf(coursesPageCount));
    return jsonObject.toString();
  }

  public String getExperimentalDocument(String experimentalId) {
    ExperimentalDocument experimentalDocument = this.experimentalDocumentDao.getExperimentalDocumentById(experimentalId);
    if (experimentalDocument == null) {
      return "error:没有该实验！";
    }
    return experimentalDocument.toString();
  }

  public String uploadExperimentalEnvironment(User user, MultipartFile experimentalEnvironment, String documentId) {
    if (user.getRole().equals("教师")) {
      if (this.experimentalDocumentDao.getExperimentalDocumentCountById(documentId) == 0) {
        return "没有该实验！";
      }
      if(this.experimentalEnvironmentDao.getExperimentalEnviromentByDocument(documentId)!=null){
        return "不要重复上传！";
      }
      long size = experimentalEnvironment.getSize();
      double sizeDouble = size / 1024.0D;
      if (sizeDouble > 5242880.0D) {
        return "上传文件超过指定大小！";
      }
      synchronized (this) {
        String name = experimentalEnvironment.getOriginalFilename();
        Timestamp time = new Timestamp(System.currentTimeMillis());
        String timeString = time.toString();
        String id = timeString.split(" ")[0].split("-")[0] + timeString.split(" ")[0].split("-")[1] + timeString.split(" ")[0].split("-")[2] + timeString.split(" ")[1].split(":")[0] + timeString.split(" ")[1].split(":")[1] + timeString.split(" ")[1].split(":")[2].split("\\.")[0];
        while (this.experimentalEnvironmentDao.getExperimentalEnvironmentCountById(id) != 0) {
          Random random = new Random(100L);
          Long idLong = Long.valueOf(Long.parseLong(id));
          idLong = Long.valueOf(idLong.longValue() + random.nextLong());
          id = idLong + "";
          if (id.length() > 14) {
            id = id.substring(0, 15);
          }
        }
        String path = this.userResourcesUrl + "document/experimental_environment/" + documentId + "/" + id + "/";
        String uploadResult = this.fileService.uploadFile(experimentalEnvironment, name, path);
        String dockerfilePath = path + name;
        String imageId = null;
        try {
          System.out.println("111");
          int resCode = DockerImageAPI.buileByDockerfile(this.dockerServerIp, dockerfilePath, name.split("\\.")[0] + "/" + documentId, "lasted");
          System.out.println(resCode);
          System.out.println(dockerfilePath);
          System.out.println(name + documentId);
          if (resCode != 200) {
            return "创建失败!错误码:" + resCode;
          }
          String imageInfo = DockerImageAPI.queryAllImageInfo(this.dockerServerIp);

          JSONArray jsonArray = new JSONArray(imageInfo);
          for (int i = 0; i < jsonArray.length(); i++) {
            JSONObject jsonObject = new JSONObject(jsonArray.get(i).toString());
            System.out.println(jsonObject.toString());
            JSONArray jsonArray1 = new JSONArray(jsonObject.get("RepoTags").toString());
            for (int j = 0; j < jsonArray1.length(); j++) {
              System.out.println(jsonArray1.get(j).toString());
              if ((name.split("\\.")[0] + "/" + documentId + ":lasted").equals(jsonArray1.get(j).toString())) {
                imageId = jsonObject.get("Id").toString();
                break;
              }
            }
            if (imageId != null) {
              break;
            }
            if (i == jsonArray.length() - 1) {
              Thread.sleep(1000L);
              jsonArray = new JSONArray(DockerImageAPI.queryAllImageInfo(this.dockerServerIp));
              i = -1;
            }
          }
        } catch (Exception e) {
          System.out.println(e);
          return "创建失败!请求镜像出错!";
        }
        System.out.println(imageId);
        imageId = imageId.split(":")[1];
        if (uploadResult.equals("ok")) {
          ExperimentalEnvironment experimentalEnvironment1 = new ExperimentalEnvironment();
          experimentalEnvironment1.setId(id);
          experimentalEnvironment1.setName(name);
          experimentalEnvironment1.setStatus("已上传");
          experimentalEnvironment1.setDocument(documentId);
          experimentalEnvironment1.setSize(sizeDouble);
          experimentalEnvironment1.setCreateTime(time);
          experimentalEnvironment1.setImageId(imageId);
          try {
            this.experimentalEnvironmentDao.createExperimetalEnvironment(experimentalEnvironment1);
          } catch (Exception e) {
            System.out.println(e.getMessage());
            String deleteFile = this.fileService.deleteFile(path + name);
            System.out.println(deleteFile);
            return "操作数据库失败！";
          }
          try {
            this.experimentalDocumentDao.updateModificationTimeById(documentId, time);
          } catch (Exception e) {
            System.out.println(e.getMessage());
          } finally {
            return "上传成功！";
          }
        }
        return uploadResult;
      }
    }
    return "您的身份是" + user.getRole() + ", 仅教师可以发布实验环境";
  }

  public String getCourseExperimentalEnvironment(String documentId) {
    if (this.experimentalDocumentDao.getExperimentalDocumentCountById(documentId) == 0) {
      return "没有该实验！";
    }
    if (this.experimentalEnvironmentDao.getExperimentalEnvironmentCountByDocument(documentId) == 0) {
      return "该课程暂没有上传实验环境！";
    }
    List<ExperimentalEnvironment> experimentalEnvironmentList = this.experimentalEnvironmentDao.getExperimentalEnviromentByDocument(documentId);
    if (experimentalEnvironmentList == null) {
      return "该课程暂没有上传实验环境！";
    }
    JSONObject jsonObject = new JSONObject();
    jsonObject.accumulate("experimentalEnvironmentList", experimentalEnvironmentList);
    return jsonObject.toString();
  }

  public String sendExperimentalEnvironment(String experimentalEnvironmentId, User user) {
    if (user.getRole().equals("教师")) {
      if (this.experimentalEnvironmentDao.getExperimentalEnvironmentCountById(experimentalEnvironmentId) == 0) {
        return "没有该实验环境！";
      }
      ExperimentalEnvironment experimentalEnvironment = this.experimentalEnvironmentDao.getExperimentalEnvironmentById(experimentalEnvironmentId);
      if (experimentalEnvironment == null) {
        return "没有该实验环境！";
      }
      String path = this.userResourcesUrl + "course/experimental_environment/" + experimentalEnvironment.getDocument() + "/" + experimentalEnvironment.getId() + "/" + experimentalEnvironment.getName();
      List<ExperimentalNode> experimentalNodeList = this.vncService.getAllExperimentalNode();
      if (experimentalNodeList == null) {
        return "没有节点！";
      }
      String errorReqult = "";
      Boolean ftpSuccess = Boolean.valueOf(true);
      for (ExperimentalNode experimentalNode : experimentalNodeList) {
        String result = this.sftpService.uploadFile(this.experimentalEnvironmentUrl, path, experimentalEnvironment.getName(), this.username, this.password, experimentalNode.getIp(), this.sftpPort.intValue());
        if (!result.equals("ok")) {
          ftpSuccess = Boolean.valueOf(false);
          errorReqult = errorReqult + result + "\n";
        }
      }
      if (ftpSuccess.booleanValue()) {
        try {
          this.experimentalEnvironmentDao.updateStatusById("已发送", experimentalEnvironmentId);
          return "ok";
        } catch (Exception e) {
          System.out.println(e.getMessage());
          return "已发送成功，但操作数据库失败，导致状态为改变！";
        }
      }
      return errorReqult;
    }
    return "抱歉，您的身份是" + user.getRole() + "，仅有教师可以发送实验环境！";
  }

  public String deleteExperimentalEnvironment(String experimentalEnvironmentId, User user) {
    if (user.getRole().equals("教师")) {
      if (this.experimentalEnvironmentDao.getExperimentalEnvironmentCountById(experimentalEnvironmentId) == 0) {
        return "没有该实验环境！";
      }
      ExperimentalEnvironment experimentalEnvironment = this.experimentalEnvironmentDao.getExperimentalEnvironmentById(experimentalEnvironmentId);
      if (experimentalEnvironment == null) {
        return "没有该实验环境！";
      }
      String path = this.userResourcesUrl + "course/experimental_environment/" + experimentalEnvironment.getDocument() + "/" + experimentalEnvironment.getId() + "/" + experimentalEnvironment.getName();
      String deleteFileResult = this.fileService.deleteFile(path);
      if ((deleteFileResult.equals("ok")) || (deleteFileResult.equals("删除文件失败：文件不存在！"))) {
        if (deleteFileResult.equals("删除文件失败：文件不存在！")) {
          System.out.println(deleteFileResult);
        }
        try {
          this.experimentalEnvironmentDao.deleteExperimentalEnvironmentById(experimentalEnvironmentId);
          return "ok";
        } catch (Exception e) {
          System.out.println(e.getMessage());
          return "删除实验环境失败：操作数据库失败，但实验环境文件已经被删除！";
        }
      }
      return deleteFileResult;
    }
    return "抱歉，您的身份是" + user.getRole() + "，仅有教师可以删除实验环境！";
  }

  public String getTeacherCourses(String teacherId, String page) {
    int pageInt = 1;
    try {
      pageInt = Integer.parseInt(page);
    } catch (Exception e) {
      return "页数无法转换为整数！";
    }
    User user = this.userDao.getUser(teacherId);
    if (user == null) {
      return "没有该教师！";
    }
    if (user.getRole().equals("教师")) {
      int coursesCount = this.courseDao.getCoursesCountByTeacher(teacherId);
      if (coursesCount == 0) {
        return "暂没有课程内容！";
      }
      if (coursesCount <= (pageInt - 1) * this.coursePageAmount) {
        return "超出页数！";
      }
      List<Course> courseList = this.courseDao.getCoursesByTeacherAndPage(teacherId, pageInt);
      int pageCount = coursesCount % this.teacherCoursePageAmount == 0 ? coursesCount / this.teacherCoursePageAmount : coursesCount / this.teacherCoursePageAmount + 1;
      JSONObject jsonObject = new JSONObject();
      jsonObject.accumulate("pageCount", Integer.valueOf(pageCount));
      jsonObject.accumulate("courseList", courseList);
      return jsonObject.toString();
    }
    return "没有该教师！";
  }

  public String uploadExperimentalReport(String experimentalId, String experimentalRepoetTitle, MultipartFile experimentalReportFile, String studentId, String studentName) {
    if ((experimentalId == null) || (experimentalId.equals("")) || (experimentalId.length() == 0)) {
      return "没有找到相关实验！";
    }
    if ((experimentalRepoetTitle == null) || (experimentalRepoetTitle.equals("")) || (experimentalRepoetTitle.length() == 0)) {
      return "实验报告题目不能为空！";
    }
    if (this.experimentalDocumentDao.getExperimentalDocumentCountById(experimentalId) == 0) {
      return "该实验不存在！";
    }
    if ((studentId == null) || (studentId.equals("")) || (studentId.length() == 0)) {
      return "学号不能为空";
    }
    if ((studentName == null) || (studentName.equals("")) || (studentName.length() == 0)) {
      return "姓名不能为空";
    }
    if (experimentalReportFile.isEmpty()) {
      return "文件不能为空！";
    }
    String fileName = experimentalReportFile.getOriginalFilename();
    String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
    if (fileType.equals("pdf")) {
      synchronized (this) {
        Timestamp timestamp = new Timestamp(System.currentTimeMillis());
        String timeString = timestamp.toString();
        String id = timeString.split(" ")[0].split("-")[0] + timeString.split(" ")[0].split("-")[1] + timeString.split(" ")[0].split("-")[2] + timeString.split(" ")[1].split(":")[0] + timeString.split(" ")[1].split(":")[1] + timeString.split(" ")[1].split(":")[2].split("\\.")[0];
        while (this.experimentalReportDao.getExperimentalReportCountById(id) != 0) {
          Random random = new Random(100L);
          Long idLong = Long.valueOf(Long.parseLong(id));
          idLong = Long.valueOf(idLong.longValue() + random.nextLong());
          id = idLong + "";
          if (id.length() > 14) {
            id = id.substring(0, 15);
          }
        }
        String name = id + "." + fileType;
        String uploadDir = this.userResourcesUrl + "/course/experimental_report/" + experimentalId + "/";
        String uploadResult = this.fileService.uploadFile(experimentalReportFile, name, uploadDir);
        if (uploadResult.equals("ok")) {
          ExperimentalReport experimentalReport = new ExperimentalReport();
          experimentalReport.setId(id);
          experimentalReport.setTitle(experimentalRepoetTitle);
          experimentalReport.setName(name);
          experimentalReport.setCreateTime(timestamp);
          experimentalReport.setExperimentalId(experimentalId);
          experimentalReport.setStudentId(studentId);
          experimentalReport.setStudentName(studentName);
          try {
            System.out.println(experimentalReport.toString());
            this.experimentalReportDao.insertExperimentalReport(experimentalReport);
            return "ok";
          } catch (Exception e) {
            System.out.println(e.getMessage());
            String deleteFileResult = this.fileService.deleteFile(uploadDir + name);
            System.out.println(deleteFileResult);
            return "写入数据库时出错！";
          }
        }
        return uploadResult;
      }
    }
    return "上传的文档必须为pdf格式！";
  }

  public String getExperimentalReport(String experimentalId, String page, User user) {
    if (user.getRole().equals("教师")) {
      int pageInt = 1;
      int experimentalReportCount = 0;
      try {
        pageInt = Integer.parseInt(page);
      } catch (Exception e) {
        return "页数出错！";
      }
      if (this.experimentalDocumentDao.getExperimentalDocumentCountById(experimentalId) == 0) {
        return "没有该实验！";
      }
      experimentalReportCount = this.experimentalReportDao.getExperimentalReportCountByExperimentalId(experimentalId);
      if (experimentalReportCount == 0) {
        return "没有实验报告！";
      }
      if (experimentalReportCount <= (pageInt - 1) * this.experimentalReportPageAmount) {
        return "超出页数！";
      }
      int pageCount = experimentalReportCount % this.experimentalReportPageAmount == 0 ? experimentalReportCount / this.experimentalReportPageAmount : experimentalReportCount / this.experimentalReportPageAmount + 1;
      List<ExperimentalReport> experimentalReportList = this.experimentalReportDao.getExperimentalReportByExperimentalIdAndStartLimitAndEndLimit(experimentalId, (pageInt - 1) * this.experimentalReportPageAmount, this.experimentalReportPageAmount);
      JSONObject jsonObject = new JSONObject();
      jsonObject.accumulate("experimentalReportList", experimentalReportList);
      jsonObject.accumulate("pageCount", Integer.valueOf(pageCount));
      jsonObject.accumulate("experimentalReportCount", Integer.valueOf(experimentalReportCount));
      return jsonObject.toString();
    }
    return "抱歉，您的身份是" + user.getRole() + "，仅有教师可以查看实验报告！";
  }

  public String getExperimentalReportTop5(String experimentalId) {
    if (this.experimentalDocumentDao.getExperimentalDocumentCountById(experimentalId) == 0) {
      return "没有该实验！";
    }
    if (this.experimentalReportDao.getExperimentalReportCountByExperimentalId(experimentalId) == 0) {
      return "暂无实验报告！";
    }
    List<ExperimentalReport> experimentalReportList = this.experimentalReportDao.getExperimentalReportByExperimentalIdAndStartLimitAndEndLimit(experimentalId, 0, 5);
    JSONObject jsonObject = new JSONObject();
    jsonObject.accumulate("experimentalReportList", experimentalReportList);
    return jsonObject.toString();
  }

  public String getExperimentalReportInformation(String experimentalReportId, User user) {
    if (user.getRole().equals("教师")) {
      if (this.experimentalReportDao.getExperimentalReportCountById(experimentalReportId) == 0) {
        return "没有该实验报告！";
      }
      JSONObject json = new JSONObject();
      ExperimentalReport experimentalReport = this.experimentalReportDao.getExperimentalReportById(experimentalReportId);
      json.accumulate("experimentalId", experimentalReport.getExperimentalId());
      json.accumulate("id", experimentalReport.getExperimentalId());
      json.accumulate("title", experimentalReport.getTitle());
      String experimentalReportSrc = "/user/course/experimental_report/" + experimentalReport.getExperimentalId() + "/" + experimentalReport.getName();
      JSONObject jsonObject = new JSONObject();
      jsonObject.accumulate("experimentalReport", json.toString());
      jsonObject.accumulate("experimentalReportSrc", experimentalReportSrc);
      return jsonObject.toString();
    }
    return "抱歉，您的身份是" + user.getRole() + "，仅有教师可以查看实验报告！";
  }

  public String deleteExperimentalReport(String experimentalReportId, User user) {
    if (user.getRole().equals("教师")) {
      if (this.experimentalReportDao.getExperimentalReportCountById(experimentalReportId) == 0) {
        return "没有该实验报告！";
      }
      ExperimentalReport experimentalReport = this.experimentalReportDao.getExperimentalReportById(experimentalReportId);
      String experimentalReportSrc = this.userResourcesUrl + "/course/experimental_report/" + experimentalReport.getExperimentalId() + "/" + experimentalReport.getName();
      String deleteFileResult = this.fileService.deleteFile(experimentalReportSrc);
      if ((deleteFileResult.equals("ok")) || (deleteFileResult.equals("删除文件失败：文件不存在！"))) {
        if (deleteFileResult.equals("删除文件失败：文件不存在！")) {
          System.out.println(deleteFileResult);
        }
        try {
          this.experimentalReportDao.deleteExperimentalReportById(experimentalReportId);
          return "ok";
        } catch (Exception e) {
          System.out.println(e.getMessage());
          return "操作数据库失败！但是实验报告已经删除！";
        }
      }
      return deleteFileResult;
    }
    return "抱歉，您的身份为" + user.getRole() + "，仅有教师可以删除实验报告！";
  }

  public String uploadExperimentalReportScore(String id, String score) {
    this.experimentalReportDao.updateExperimentalReportScoreById(id, score);
    System.out.println("ok");
    return "ok";
  }

  public String getExperimentalScore(String experimentalId) {
    List<ExperimentalReport> experimentalReportsList = this.experimentalReportDao.getExperimentalReportByExperimentalId(experimentalId);
    if (experimentalReportsList.isEmpty()) {
      return "没有该实验";
    }
    ArrayList<String> experimentalReportArrayList = new ArrayList();
    for (int i = 0; i < experimentalReportsList.size(); i += 1) {
      JSONObject jsonObject = new JSONObject();
      jsonObject.accumulate("studentId", ((ExperimentalReport) experimentalReportsList.get(i)).getStudentId());
      jsonObject.accumulate("studentName", ((ExperimentalReport) experimentalReportsList.get(i)).getStudentName());
      jsonObject.accumulate("experimentalScore", ((ExperimentalReport) experimentalReportsList.get(i)).getExperimentalScore());
      System.out.println(jsonObject.toString());
      experimentalReportArrayList.add(jsonObject.toString());
    }
    JSONArray jsonArray = new JSONArray(experimentalReportArrayList);
    return jsonArray.toString();
  }

  public String uploadExperimentalCheckWork(ExperimentalCheckWork experimentalCheckWork) {
    String statu = this.experimentalCheckWorkDao.insertSignIn(experimentalCheckWork);
    return statu;
  }

  public String getCheckWorkDate(String mouth, String year, String courseId) {
    String dateString = year + "-" + mouth;
    List<ExperimentalCheckWork> list = this.experimentalCheckWorkDao.getCheckWorkDateByDateString(dateString, courseId);
    List<String> jsonlist = new ArrayList();
    for (int i = 0; i < list.size(); i++) {
      jsonlist.add(((ExperimentalCheckWork) list.get(i)).toString());
    }
    JSONArray jsonArray = new JSONArray(jsonlist);
    return jsonArray.toString();
  }

  public String takeScoreToExcel(String coureseId) {
    List<ExperimentalDocument> experimentalDocumentsList = this.experimentalDocumentDao.getExperimentalDocumentByCourseId(coureseId);
    List<String> experimentalReportList = new ArrayList();
    for (int i = 0; i < experimentalDocumentsList.size(); i++) {
      String experimentalId = ((ExperimentalDocument) experimentalDocumentsList.get(i)).getId();
      List<ExperimentalReport> l = new ArrayList();
      l = this.experimentalReportDao.getExperimentalReportByExperimentalId(experimentalId);
      for (int j = 0; j < l.size(); j++) {
        if (((ExperimentalReport) l.get(j)).getExperimentalScore() != null) {
          experimentalReportList.add(((ExperimentalReport) l.get(j)).toString());
        }
      }
    }
    JSONArray jsonArray = new JSONArray(experimentalReportList);
    JSONObject jsonObject = new JSONObject();
    jsonObject.accumulate("jsonArray", jsonArray.toString());
    jsonObject.accumulate("courseName", ((ExperimentalDocument) experimentalDocumentsList.get(0)).getTitle());
    return jsonObject.toString();
  }

  public List<StudentUser> parseXSSFExcelToStudentUser(MultipartFile file, String teacherName) {
    List<String> name = new ArrayList();
    List<String> studentId = new ArrayList();
    List<StudentUser> studentUserList = new ArrayList();
    try {
      XSSFWorkbook workbook = new XSSFWorkbook(file.getInputStream());

      XSSFSheet sheet = workbook.getSheetAt(0);
      for (int i = 1; !StringUtils.isEmpty(sheet.getRow(i)); i++) {
        XSSFRow row = sheet.getRow(i);
        for (int j = 0; !StringUtils.isEmpty(row.getCell(j)); j++) {
          XSSFCell cell = row.getCell(j);
          if (j == 0) {
            name.add(cell.toString());
          }
          if (j == 1) {
            studentId.add(cell.toString().split("\\.")[0]);
          }
          if (j > 1) {
            return null;
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    for (int i = 0; i < name.size(); i++) {
      StudentUser studentUser = new StudentUser();
      studentUser.setClassId("0");
      studentUser.setPassWord((String) studentId.get(i));
      studentUser.setStudentId((String) studentId.get(i));
      studentUser.setteacherName(teacherName);
      studentUser.setTel("13888888888");
      studentUser.setStudentName((String) name.get(i));
      studentUser.setTimestamp(new Timestamp(System.currentTimeMillis()));
      if (!this.studentUserDao.isStudentUser((String) studentId.get(i)).booleanValue()) {
        studentUserList.add(studentUser);
      }
    }
    return studentUserList;
  }
}
